#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>


#define FILE_BUFF 1024
#define LISTEN_BACKLOG 50
#define PRINT(x,args...)\
printf("[%s %d]: %s",__FILE__,__LINE__,x,##args);

#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)

const char *skip_blink(const char *buff)
{
	while(*buff == ' ')++buff;
	return buff;
}

const char *anti_skip_blink(const char *buff)
{
	while(buff[0] != ' ')++buff;
	return buff;
}

void parse(const char *buff)
{
	const char *sec = buff;
	const char *fst = buff;
	char res[1024];
	
	strcpy(res, "method: ");
	fst = anti_skip_blink(sec);
	strncat(res, buff, fst - sec);
	strncat(res, "\n", 1);
	
	fst = skip_blink(fst);
	sec = fst;
	fst = anti_skip_blink(fst);
	strncat(res, sec, fst - sec);
	strncat(res, "\n", 1);
	
	strcat(res, "");
	printf("%s\n",res);
}

void main()
{
	socklen_t  peer_addr_size; 
	int b_serv_fd, cfd;
	char bufff[1024];
	memset(bufff, 0, 1024);
	struct sockaddr_in  my_addr, peer_addr;
	int sock_opt = 1;
	int rtn;
	char *buff;
	FILE *file;
	char file_buff[FILE_BUFF];
	
	b_serv_fd = socket(AF_INET, SOCK_STREAM, 0);	
	if ( -1 == b_serv_fd ) {
		perror("socket");	
		return ;
	}
	rtn = setsockopt(b_serv_fd, SOL_SOCKET, SO_REUSEADDR, &sock_opt, sizeof(sock_opt));
	printf("b serv socket ok\n");
	memset(&my_addr, 0, sizeof(struct sockaddr_in));
	/* Clear structure */
	my_addr.sin_family=AF_INET;
	my_addr.sin_port=htons(9090);
	my_addr.sin_addr.s_addr = INADDR_ANY;
	if (bind(b_serv_fd, (struct sockaddr *) &my_addr,
		sizeof(struct sockaddr_in)) == -1)
		handle_error("bind");
	
	if (listen(b_serv_fd, LISTEN_BACKLOG) == -1)
		handle_error("listen");
	
	peer_addr_size = sizeof(struct sockaddr_in);
	
	cfd = accept(b_serv_fd, (struct sockaddr *) &peer_addr,
		&peer_addr_size);
	if (cfd == -1)
			handle_error("accept");
	file = fopen("index.html","r");
	rtn = fread(file_buff, sizeof(char), FILE_BUFF, file);
	for (;;) {
		static a = 0;
		
		
		if(-1 == recv(cfd, bufff, 1024, 0) )
			handle_error("recvfrom");
		
		printf("-----------%d- HTTP  start--------------------\n", a);
		printf("%s\n", bufff);
		printf("-----------%d--HTTP  end-----------------\n", a++);
		//  parse(bufff);
		
		send(cfd, file_buff, rtn, 0);
		
	}
	fclose(file);
	close(cfd);
	close(b_serv_fd);
	
}

